<script setup lang="ts">
import type { Key } from 'ant-design-vue/es/vc-tree/interface';

import type { Nullable } from '@vben/types';

import type {
  ContextMenuItem,
  TreeActionItem,
  TreeActionType,
  TreeItem,
} from '#/components/tree';

import { onMounted, ref, unref } from 'vue';

import { Button, Checkbox } from 'ant-design-vue';

import { IotCustomersApi } from '#/api/iot/customers/iotCustomers';
import { BasicTree } from '#/components/tree';
import { $t } from '#/locales';
import {
  eachTree,
  findChildrenByParentId,
  findNodeByKey,
} from '#/utils/helper/treeHelper';

defineOptions({
  name: '客户树结构',
  inheritAttrs: false,
});
const emit = defineEmits<Emits>();
interface Emits {
  (e: 'select', parent: TreeItem, current: TreeItem, childrenIds: Key[]): void;

  (e: 'reset'): void;
}

const treeRef = ref<Nullable<TreeActionType>>(null);
const treeData = ref<TreeItem[]>([]);
const treeLoading = ref<boolean>(false);
const recursion = ref<boolean>(false);

function getTree() {
  const treeR = unref(treeRef);
  if (!treeR) {
    throw new Error('树结构加载失败,请刷新页面');
  }
  return treeR;
}

onMounted(() => {
  fetch();
});

// 加载数据
async function fetch() {
  try {
    treeLoading.value = true;
    treeData.value = (await IotCustomersApi.treeToDevice(
      {},
    )) as unknown as TreeItem[];
    eachTree(
      treeData.value,
      (item) => {
        item.key = item.id;
        item.title = item.name;
        item.slots = { titleBefore: 'titleBefore' };
        return item;
      },
      {},
    );
    setTimeout(() => {
      getTree().filterByLevel(2);
    }, 0);
  } finally {
    treeLoading.value = false;
  }
}

// 选择节点
function handleSelect(keys: Key[]) {
  if (keys[0]) {
    const node = findNodeByKey(keys[0], treeData.value);
    const parent = findNodeByKey(node?.parentId, treeData.value);
    let childrenIds: Key[] = [];
    childrenIds = recursion.value
      ? findChildrenByParentId(keys[0], treeData.value)
      : [node.id];
    emit('select', parent, node, childrenIds);
  }
}

const actionList: TreeActionItem[] = [];
const getRightMenuList = (_: any): ContextMenuItem[] => {
  return [];
};

// 重置
function handleReset() {
  getTree().setSelectedKeys([]);
  emit('reset');
}

// 选择 本级及子级
function handleQuery() {
  handleSelect(getTree().getSelectedKeys() as string[]);
}

defineExpose({ fetch });
</script>

<template>
  <div class="overflow-hidden">
    <div class="mb-1">
      <Button class="mr-2" type="primary" @click="handleReset()">重置</Button>
      <Checkbox v-model:checked="recursion" @change="handleQuery()">
        本级及子级
      </Checkbox>
    </div>

    <BasicTree
      ref="treeRef"
      :field-names="{ key: 'id', title: 'name' }"
      :action-list="actionList"
      :before-right-click="getRightMenuList"
      :click-row-to-expand="false"
      :loading="treeLoading"
      checkable
      :title="$t('basic.user.baseOrg.table.title')"
      :tree-data="treeData"
      check-strictly
      highlight
      search
      toolbar
      @select="handleSelect"
    />
  </div>
</template>
<style lang="scss" scoped></style>
